package com.netease.ssm.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.netease.ssm.cons.CommonConstant;
import com.netease.ssm.meta.User;
import com.netease.ssm.service.UserService;

@Controller
public class LoginController extends BaseController{
     
	 @Autowired
     private UserService userService;
	 
	 @RequestMapping(value="/login",method = RequestMethod.GET)
	 private String loginPage(){
			return "login";
		}
	 @RequestMapping(value = "/api/login",method = RequestMethod.POST)
	 public ModelAndView login(HttpServletRequest request,User user){
		 User dbUser = userService.getPersonByUserName(user.getUserName());
		 System.out.println(user.getUserName());
		 ModelAndView mav = new ModelAndView();
		 if(dbUser==null){
			 mav.addObject("code", 401);
			 mav.addObject("message", "faile");
			 mav.addObject("result", false);
		 }else if(!dbUser.getPassword().equals(user.getPassword())){
			 mav.addObject("code", 401);
			 mav.addObject("message", "faile");
			 mav.addObject("result", false);
		 }else{
			 setSessionPerson(request,dbUser);
			 mav.addObject("code", 200);
			 mav.addObject("message", "success");
			 mav.addObject("result", true);
		 }
		return mav;
	 }
	 @RequestMapping(value="/logout",method = RequestMethod.GET)
	 public String logout(HttpSession session){
		 session.removeAttribute(CommonConstant.USER_CONTEXT);
		 return "redirect:/login";
	 }
	
}
